import { ref } from 'vue'
import { defineStore } from 'pinia'
import { loginApi } from '@/apis/users'
import { useCartStore } from './cart'
import { mergeCartAPI } from '@/apis/cart'

export const useUserStore = defineStore('user', () => {
    const userInfo = ref({})
    const cartStore = useCartStore()
    const getUserInfo = async ({ account, password }) => {
        const res = await loginApi({ account, password })
        userInfo.value = res.result
        //登录时合并数据
        //合并购物车的操作
        await mergeCartAPI(cartStore.cartList.map(item => {
            return {
                skuId: item.skuId,
                selected: item.selected,
                count: item.count
            }
        }))
        //获取最新的购物车列表
        cartStore.updateNewList()
    }

    const clearUserInfo = () => {
        userInfo.value = {}
        cartStore.clearCart()
    }

    return {
        userInfo,
        getUserInfo,
        clearUserInfo
    }

}, {
    persist: true
})
